#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据导出相关路由
"""
import csv
import io
from datetime import datetime
from fastapi import APIRouter, Request
from fastapi.responses import Response

from ..database import get_db_connection, rows_to_dict_list
from ..auth.session import verify_admin

router = APIRouter()


@router.get("/api/export/password_template")
async def export_password_template():
    """导出密码模板API"""
    # 生成CSV模板
    output = io.StringIO()
    writer = csv.writer(output)
    
    # 写入标题行
    writer.writerow(['url', 'account', 'password', 'description'])
    
    csv_content = output.getvalue()
    output.close()
    
    # 返回CSV文件
    response = Response(
        content=csv_content.encode('utf-8-sig'),
        media_type='text/csv',
        headers={
            'Content-Disposition': 'attachment; filename="password_template.csv"'
        }
    )
    
    return response


@router.get("/api/export/password_sample")
async def export_password_sample():
    """导出密码示例API"""
    # 生成CSV示例
    output = io.StringIO()
    writer = csv.writer(output)
    
    # 写入标题行
    writer.writerow(['url', 'account', 'password', 'description'])
    
    # 写入示例数据
    sample_data = [
        ['https://www.google.com', 'user@gmail.com', 'GooglePass123!', 'Google账号'],
        ['https://www.facebook.com', 'myemail@example.com', 'FbPassword456@', 'Facebook社交账号'],
        ['https://www.github.com', 'developer123', 'GitHubSecure789#', '代码仓库账号'],
        ['https://www.linkedin.com', 'professional@work.com', 'LinkedPass321$', '职业社交网络'],
        ['https://www.amazon.com', 'shopper@email.com', 'AmazonBuy654%', '购物网站账号'],
        ['https://www.netflix.com', 'viewer@home.com', 'NetflixWatch987^', '视频流媒体'],
        ['https://www.dropbox.com', 'storage@cloud.com', 'DropboxFile147&', '云存储服务'],
        ['https://www.spotify.com', 'music@lover.com', 'SpotifyMusic258*', '音乐流媒体'],
        ['https://www.twitter.com', 'tweeter@social.com', 'TwitterPost369(', '微博社交'],
        ['https://www.instagram.com', 'photo@gram.com', 'InstaPhoto741)', '图片社交']
    ]
    
    for row in sample_data:
        writer.writerow(row)
    
    csv_content = output.getvalue()
    output.close()
    
    # 返回CSV文件
    response = Response(
        content=csv_content.encode('utf-8-sig'),
        media_type='text/csv',
        headers={
            'Content-Disposition': 'attachment; filename="password_sample.csv"'
        }
    )
    
    return response


@router.get("/api/export/passwords")
async def export_passwords(request: Request):
    """导出所有密码API（管理员）"""
    verify_admin(request)
    
    conn = get_db_connection()
    passwords = conn.execute("""
        SELECT p.url, p.account, p.password, p.description, p.created_at, p.updated_at,
               u.username as user_name
        FROM passwords p
        JOIN users u ON p.user_id = u.id
        ORDER BY p.created_at DESC
    """).fetchall()
    conn.close()
    
    # 生成CSV内容
    output = io.StringIO()
    writer = csv.writer(output)
    
    # 写入标题行
    writer.writerow(['URL', '账号', '密码', '描述', '所属用户', '创建时间', '更新时间'])
    
    # 写入数据行
    for password in passwords:
        writer.writerow([
            password['url'],
            password['account'],
            password['password'],
            password['description'] or '',
            password['user_name'],
            password['created_at'],
            password['updated_at']
        ])
    
    csv_content = output.getvalue()
    output.close()
    
    # 返回CSV文件
    response = Response(
        content=csv_content.encode('utf-8-sig'),
        media_type='text/csv',
        headers={
            'Content-Disposition': f'attachment; filename="all_passwords_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv"'
        }
    )
    
    return response


@router.get("/api/export/shares")
async def export_shares(request: Request):
    """导出分享记录API（管理员）"""
    verify_admin(request)
    
    conn = get_db_connection()
    shares = conn.execute("""
        SELECT ps.share_token, ps.access_count, ps.expires_at, ps.created_at,
               p.url, p.account, p.description, u.username as user_name
        FROM password_shares ps
        JOIN passwords p ON ps.password_id = p.id
        JOIN users u ON p.user_id = u.id
        ORDER BY ps.created_at DESC
    """).fetchall()
    conn.close()
    
    # 生成CSV内容
    output = io.StringIO()
    writer = csv.writer(output)
    
    # 写入标题行
    writer.writerow(['分享令牌', 'URL', '账号', '描述', '所属用户', '访问次数', '过期时间', '创建时间'])
    
    # 写入数据行
    for share in shares:
        writer.writerow([
            share['share_token'],
            share['url'],
            share['account'],
            share['description'] or '',
            share['user_name'],
            share['access_count'],
            share['expires_at'] or '永不过期',
            share['created_at']
        ])
    
    csv_content = output.getvalue()
    output.close()
    
    # 返回CSV文件
    response = Response(
        content=csv_content.encode('utf-8-sig'),
        media_type='text/csv',
        headers={
            'Content-Disposition': f'attachment; filename="shares_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv"'
        }
    )
    
    return response